<script setup lang="ts">
import type { VisitorApi } from '#/api';

import { computed, onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';

import { message } from 'ant-design-vue';

import {
  getTalentCountApi,
  getTalentListApi,
  updateTalentFavoriteApi,
} from '#/api';

defineOptions({ name: 'VisitorManagement' });

interface TabInfo {
  key: string;
  label: string;
  count: number;
}

interface TalentTableItem {
  id: string;
  realName: string;
  sexText: string;
  phone: string;
  email: string;
  professionText: string;
  cityText: string;
  expertiseList: string[];
  skillList: string[];
  experienceYears: number;
  status: string;
  statusText: string;
  collected: number;
  summary: string;
  avator: string;
  enterpriseText: string;
}

const router = useRouter();

const loading = ref(false);
const searchKeyword = ref('');
const activeTab = ref('my-visitors');

const tabs = ref<TabInfo[]>([
  { key: 'my-visitors', label: '我的游人', count: 0 },
  { key: 'my-favorites', label: '我的收藏', count: 0 },
  { key: 'testing', label: '测试中', count: 0 },
  { key: 'assigned', label: '外派中', count: 0 },
  { key: 'completed', label: '完成', count: 0 },
]);

const tableData = ref<TalentTableItem[]>([]);
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
});

const statusStyleMap: Record<string, { class: string; text: string }> = {
  空闲: { text: '空闲', class: 'bg-green-100 text-green-800' },
  测试中: { text: '测试中', class: 'bg-blue-100 text-blue-800' },
  外派中: { text: '外派中', class: 'bg-orange-100 text-orange-800' },
  完成: { text: '完成', class: 'bg-gray-100 text-gray-800' },
};

const statusTabMap: Record<string, string> = {
  testing: 'testing',
  assigned: 'assigned',
  completed: 'completed',
};

const isFavoriteTab = computed(() => activeTab.value === 'my-favorites');

function parseToList(value?: null | string) {
  if (!value) return [] as string[];
  return value
    .split(/[,|;、\s]+/)
    .map((item) => item.trim())
    .filter(Boolean);
}

function getStatusInfo(statusText: string) {
  return (
    statusStyleMap[statusText] ?? {
      text: statusText || '未知',
      class: 'bg-gray-100 text-gray-600',
    }
  );
}

async function fetchVisitorList() {
  loading.value = true;
  try {
    const payload: VisitorApi.TalentListParams = {
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      keyword: searchKeyword.value || '',
      profession: [],
      expertiseField: [],
      skillTags: [],
      // experienceYearsStart: 0,
      // experienceYearsEnd: 50,
      sex: '',
      status: '',
      isFavorite: isFavoriteTab.value ? 1 : 0,
      queryAll: 0,
    };

    if (statusTabMap[activeTab.value]) {
      payload.status = statusTabMap[activeTab.value];
    }

    const result = await getTalentListApi(payload);

    pagination.total = result?.total ?? 0;
    pagination.pageSize = payload.pageSize;
    pagination.current = result?.current || payload.pageNo;

    const records = result?.records ?? [];
    tableData.value = records.map((item) => ({
      id: item.id,
      realName: item.realName,
      sexText: item.sex_dictText || item.sex || '-',
      phone: item.phone,
      email: item.email,
      professionText: item.profession_dictText || item.profession || '-',
      cityText: item.city_dictText || item.city || '-',
      expertiseList: parseToList(
        item.expertiseField_dictText || item.expertiseField,
      ),
      skillList: parseToList(item.skillTags_dictText || item.skillTags),
      experienceYears: item.experienceYears,
      status: item.status,
      statusText: item.status_dictText || item.status || '-',
      collected: item.collected,
      summary: item.summary,
      avator: item.avator,
      enterpriseText: item.enterprise_dictText || item.enterprise || '-',
    }));
  } catch (error) {
    console.error('获取游人列表失败:', error);
    message.error('获取游人列表失败，请稍后重试');
  } finally {
    loading.value = false;
  }
}

async function fetchTalentCount() {
  try {
    const result = await getTalentCountApi();
    tabs.value = [
      {
        key: 'my-visitors',
        label: '我的游人',
        count: result?.data?.total ?? 0,
      },
      {
        key: 'my-favorites',
        label: '我的收藏',
        count: result?.data?.favorite ?? 0,
      },
      { key: 'testing', label: '测试中', count: result?.data?.testing ?? 0 },
      { key: 'assigned', label: '外派中', count: result?.data?.external ?? 0 },
      { key: 'completed', label: '完成', count: result?.data?.finished ?? 0 },
    ];
  } catch (error) {
    console.error('获取人才统计失败:', error);
  }
}

function handleSearch() {
  pagination.current = 1;
  fetchVisitorList();
}

function handleTabChange(tabKey: string) {
  activeTab.value = tabKey;
  pagination.current = 1;
  fetchVisitorList();
}

async function toggleCollect(visitor: TalentTableItem) {
  const target = visitor.collected === 1 ? 0 : 1;
  try {
    await updateTalentFavoriteApi({
      talentId: visitor.id,
      isFavorite: target as 0 | 1,
    });
    visitor.collected = target;
    message.success(target === 1 ? '已添加收藏' : '已取消收藏');

    if (isFavoriteTab.value && target === 0) {
      fetchVisitorList();
    }
  } catch (error) {
    console.error('更新收藏状态失败:', error);
    message.error('更新收藏状态失败，请稍后重试');
  }
}

function viewVisitorInfo(visitor: TalentTableItem) {
  router.push({
    name: 'VisitorDetail',
    params: { id: visitor.id },
  });
}

function shareVisitor(visitor: TalentTableItem) {
  const shareUrl = new URL(
    `/#/visitor-share/${visitor.id}`,
    window.location.origin,
  );
  window.open(shareUrl.toString(), '_blank', 'noopener');
}

function handlePageChange(page: number) {
  pagination.current = page;
  fetchVisitorList();
}

onMounted(() => {
  fetchTalentCount();
  fetchVisitorList();
});
</script>

<template>
  <div class="h-full bg-[#F5F3F0] bg-gray-50">
    <!-- 头部区域 -->
    <div class="ml-6 mr-6 mt-6 border-b border-gray-200 bg-white px-6 py-4">
      <!-- 标签页 -->
      <div class="mb-0 flex justify-between space-x-1">
        <div class="flex gap-1">
          <button
            v-for="tab in tabs"
            :key="tab.key"
            class="rounded-lg px-4 py-2 text-sm font-medium transition-colors"
            :class="[
              activeTab === tab.key
                ? 'bg-amber-500 text-white'
                : 'bg-gray-100 text-gray-600 hover:bg-gray-200',
            ]"
            @click="handleTabChange(tab.key)"
          >
            {{ tab.label }}
            <span
              class="ml-2 rounded-full bg-white bg-opacity-20 px-2 py-1 text-xs"
            >
              {{ tab.count }}
            </span>
          </button>
        </div>

        <!-- 搜索栏 -->
        <div class="flex items-center space-x-4">
          <div class="relative flex-1">
            <div
              class="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3"
            >
              <svg
                class="h-5 w-5 text-gray-400"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  stroke-width="2"
                  d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
                />
              </svg>
            </div>
            <input
              v-model="searchKeyword"
              type="text"
              placeholder="搜索游人姓名"
              class="w-full rounded-lg border border-gray-300 py-2 pl-10 pr-4 focus:border-transparent focus:outline-none focus:ring-2 focus:ring-amber-500"
              @keyup.enter="handleSearch"
            />
          </div>
          <!-- <button
            @click="handleSearch"
            class="rounded-lg bg-amber-500 px-4 py-2 font-medium text-white transition-colors hover:bg-amber-600"
          >
            搜索
          </button> -->
        </div>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="mx-6 mt-0 rounded-lg bg-white shadow-sm">
      <div class="overflow-x-auto">
        <table class="w-full">
          <thead class="">
            <tr>
              <th
                class="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500"
              >
                游人
              </th>
              <th
                class="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500"
              >
                性别
              </th>
              <th
                class="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500"
              >
                手机号
              </th>
              <th
                class="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500"
              >
                邮箱
              </th>
              <th
                class="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500"
              >
                游人职业
              </th>
              <th
                class="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500"
              >
                所在城市
              </th>
              <th
                class="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500"
              >
                擅长领域
              </th>
              <th
                class="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500"
              >
                技能标签
              </th>
              <th
                class="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500"
              >
                从业年限
              </th>
              <th
                class="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500"
              >
                收藏状态
              </th>
              <th
                class="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500"
              >
                游人状态
              </th>
              <th
                class="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500"
              >
                操作
              </th>
            </tr>
          </thead>
          <tbody class="divide-y divide-gray-200 bg-white">
            <tr
              v-for="visitor in tableData"
              :key="visitor.id"
              class="hover:bg-gray-50"
            >
              <!-- 游人 -->
              <td class="whitespace-nowrap px-6 py-4">
                <div class="flex items-center">
                  <div
                    class="flex h-10 w-10 items-center justify-center overflow-hidden rounded-full bg-gradient-to-r from-pink-400 to-purple-500 font-bold text-white"
                  >
                    <img
                      v-if="visitor.avator"
                      :src="visitor.avator"
                      alt="avatar"
                      class="h-full w-full object-cover"
                    />
                    <span v-else>
                      {{ visitor.realName.charAt(0) }}
                    </span>
                  </div>
                  <div class="ml-3">
                    <div class="text-sm font-medium text-gray-900">
                      {{ visitor.realName }}
                    </div>
                    <div class="text-xs text-gray-500">
                      {{ visitor.enterpriseText }}
                    </div>
                  </div>
                </div>
              </td>

              <!-- 性别 -->
              <td class="whitespace-nowrap px-6 py-4 text-sm text-gray-900">
                {{ visitor.sexText }}
              </td>

              <!-- 手机号 -->
              <td class="whitespace-nowrap px-6 py-4 text-sm text-gray-900">
                {{ visitor.phone || '-' }}
              </td>

              <!-- 邮箱 -->
              <td class="whitespace-nowrap px-6 py-4 text-sm text-gray-900">
                {{ visitor.email || '-' }}
              </td>

              <!-- 游人职业 -->
              <td class="whitespace-nowrap px-6 py-4 text-sm text-gray-900">
                {{ visitor.professionText }}
              </td>

              <!-- 所在城市 -->
              <td class="whitespace-nowrap px-6 py-4 text-sm text-gray-900">
                {{ visitor.cityText }}
              </td>

              <!-- 擅长领域 -->
              <td class="whitespace-nowrap px-6 py-4">
                <div class="flex flex-wrap gap-1">
                  <span
                    v-for="(expertise, index) in visitor.expertiseList"
                    :key="index"
                    class="inline-flex items-center rounded-full bg-blue-100 px-2 py-1 text-xs font-medium text-blue-800"
                  >
                    {{ expertise }}
                  </span>
                  <span
                    v-if="visitor.expertiseList.length === 0"
                    class="text-xs text-gray-400"
                    >-</span
                  >
                </div>
              </td>

              <!-- 技能标签 -->
              <td class="whitespace-nowrap px-6 py-4">
                <div class="flex flex-wrap gap-1">
                  <span
                    v-for="(skill, index) in visitor.skillList"
                    :key="index"
                    class="inline-flex items-center rounded-full bg-green-100 px-2 py-1 text-xs font-medium text-green-800"
                  >
                    {{ skill }}
                  </span>
                  <span
                    v-if="visitor.skillList.length === 0"
                    class="text-xs text-gray-400"
                    >-</span
                  >
                </div>
              </td>

              <!-- 从业年限 -->
              <td class="whitespace-nowrap px-6 py-4 text-sm text-gray-900">
                {{
                  visitor.experienceYears
                    ? `${visitor.experienceYears} 年`
                    : '-'
                }}
              </td>

              <!-- 收藏状态 -->
              <td class="whitespace-nowrap px-6 py-4">
                <button
                  class="rounded-full px-3 py-1 text-xs font-medium transition-colors"
                  :class="[
                    visitor.collected === 1
                      ? 'bg-yellow-400 text-white'
                      : 'border border-gray-300 bg-gray-100 text-gray-700',
                  ]"
                  @click="toggleCollect(visitor)"
                >
                  {{ visitor.collected === 1 ? '已收藏' : '未收藏' }}
                </button>
              </td>

              <!-- 游人状态 -->
              <td class="whitespace-nowrap px-6 py-4">
                <span
                  class="inline-flex items-center rounded-full px-2 py-1 text-xs font-medium"
                  :class="[getStatusInfo(visitor.statusText).class]"
                >
                  {{ getStatusInfo(visitor.statusText).text }}
                </span>
              </td>

              <!-- 操作 -->
              <td class="whitespace-nowrap px-6 py-4">
                <div class="flex items-center gap-2">
                  <button
                    class="rounded-md border border-gray-300 bg-gray-100 px-3 py-1 text-xs font-medium text-gray-700 transition-colors hover:bg-gray-200"
                    @click="viewVisitorInfo(visitor)"
                  >
                    查看信息
                  </button>
                  <button
                    class="rounded-md border border-gray-300 bg-gray-100 px-3 py-1 text-xs font-medium text-gray-700 transition-colors hover:bg-gray-200"
                    @click="shareVisitor(visitor)"
                  >
                    查看详情
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="flex items-center justify-center py-8">
        <div
          class="h-8 w-8 animate-spin rounded-full border-b-2 border-amber-500"
        ></div>
      </div>

      <!-- 空状态 -->
      <div v-else-if="tableData.length === 0" class="py-8 text-center">
        <div class="text-gray-500">
          <svg
            class="mx-auto h-12 w-12 text-gray-400"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
              d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4"
            />
          </svg>
          <h3 class="mt-2 text-sm font-medium text-gray-900">暂无数据</h3>
          <p class="mt-1 text-sm text-gray-500">没有找到符合条件的游人信息</p>
        </div>
      </div>

      <!-- 分页 -->
      <div
        v-if="!loading && tableData.length > 0"
        class="flex items-center justify-between border-t border-gray-200 bg-white px-4 py-3 sm:px-6"
      >
        <div class="flex flex-1 justify-between sm:hidden">
          <button
            :disabled="pagination.current <= 1"
            class="relative inline-flex items-center rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 disabled:cursor-not-allowed disabled:opacity-50"
            @click="handlePageChange(pagination.current - 1)"
          >
            上一页
          </button>
          <button
            :disabled="
              pagination.current >=
              Math.ceil(pagination.total / pagination.pageSize)
            "
            class="relative ml-3 inline-flex items-center rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 disabled:cursor-not-allowed disabled:opacity-50"
            @click="handlePageChange(pagination.current + 1)"
          >
            下一页
          </button>
        </div>
        <div
          class="hidden sm:flex sm:flex-1 sm:items-center sm:justify-between"
        >
          <div>
            <p class="text-sm text-gray-700">
              显示第
              <span class="font-medium">{{
                (pagination.current - 1) * pagination.pageSize + 1
              }}</span>
              到
              <span class="font-medium">{{
                Math.min(
                  pagination.current * pagination.pageSize,
                  pagination.total,
                )
              }}</span>
              条，共
              <span class="font-medium">{{ pagination.total }}</span>
              条记录
            </p>
          </div>
          <div class="flex items-center space-x-2">
            <button
              :disabled="pagination.current <= 1"
              class="relative inline-flex items-center rounded-md border border-gray-300 bg-white px-2 py-2 text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:cursor-not-allowed disabled:opacity-50"
              @click="handlePageChange(pagination.current - 1)"
            >
              <
            </button>

            <button
              v-for="page in Math.min(
                5,
                Math.ceil(pagination.total / pagination.pageSize),
              )"
              :key="page"
              class="relative inline-flex items-center rounded-md border px-4 py-2 text-sm font-medium"
              :class="[
                page === pagination.current
                  ? 'border-amber-500 bg-amber-500 text-white'
                  : 'border-gray-300 bg-white text-gray-700 hover:bg-gray-50',
              ]"
              @click="handlePageChange(page)"
            >
              {{ page }}
            </button>

            <button
              :disabled="
                pagination.current >=
                Math.ceil(pagination.total / pagination.pageSize)
              "
              class="relative inline-flex items-center rounded-md border border-gray-300 bg-white px-2 py-2 text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:cursor-not-allowed disabled:opacity-50"
              @click="handlePageChange(pagination.current + 1)"
            >
              >
            </button>

            <div class="ml-4 flex items-center space-x-2">
              <span class="text-sm text-gray-700">每页</span>
              <select
                class="rounded-md border border-gray-300 px-2 py-1 text-sm"
              >
                <option value="10">10</option>
                <option value="20">20</option>
                <option value="50">50</option>
              </select>
              <span class="text-sm text-gray-700">条</span>
            </div>

            <div class="ml-4 flex items-center space-x-2">
              <span class="text-sm text-gray-700">跳转到</span>
              <input
                type="number"
                class="w-16 rounded-md border border-gray-300 px-2 py-1 text-sm"
                :max="Math.ceil(pagination.total / pagination.pageSize)"
                @keyup.enter="
                  (e) =>
                    handlePageChange(
                      Number((e.target as HTMLInputElement).value),
                    )
                "
              />
              <button
                class="rounded-md bg-gray-100 px-3 py-1 text-sm text-gray-700 hover:bg-gray-200"
              >
                跳转
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
